package com.yuneec.droneservice.command;

import com.yuneec.droneservice.request.IResponse;
import com.yuneec.droneservice.utils.ByteUtils;
import com.yuneec.droneservice.utils.CrcUtils;

/**
 * Created by gjw on 2017/3/27.
 */

public class TransFileData extends BaseCommand {
    private byte[] fileData;
    private int off;
    private int len;
    //add u16 seq  by zzd
    private int seq;

    public TransFileData(int seq, byte[] data) {
        this(seq, data, 0, data.length);
    }

    public TransFileData(int seq, byte[] data, int off, int len) {
        super(MAV_RC_COMMAND.MAV_RC_CMD_TRANSFILEDATA);
        if (data == null || off < 0 || len <= 0 || off + len > data.length) {
            throw new IllegalArgumentException();
        }
        this.fileData = data;
        this.off = off;
        this.len = len;
        this.seq = seq;
    }

    public int getSeq() {
        return seq;
    }


    @Override
    public IResponse toResponse(byte[] data, int off, int len) {
        int code = data[off + 1] & 0xff;
        return new IResponse(ids(), code);
    }

    @Override
    public byte[] toRawData() {
        byte[] raw = new byte[6 + len + 2];
        int sendLen = this.len + 2 + 2;//seq

        raw[0] = HANDERID;
        raw[1] = getSenderId();
        ByteUtils.uShortToByteArray(raw, 2, sendLen, IS_BIGENDIAN);

        raw[4] = (byte) (ids() & 0xFF);

        raw[5] = (byte) (this.seq & 0xFF);
        raw[6] = (byte) ((this.seq >> 8) & 0xFF);

        System.arraycopy(this.fileData, this.off, raw, 7, this.len);
        byte crc = CrcUtils.crc8Table(raw, 0, raw.length - 1);
        raw[raw.length - 1] = crc;
        return raw;
    }

    @Override
    public boolean hasReply() {
        return true;
    }

}
